import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { db } from "@/db/drizzle";
import { legalDocument } from "@/db/schema";
import { eq, desc, asc, and, or } from "drizzle-orm";

const app = new Hono()
  .get("/", (c) => {
    return c.json({ user: "GET" });
  })
  .get(
    "/:caseNum",
    zValidator(
      "param",
      z.object({
        caseNum: z.string(),
      })
    ),
    async (c) => {
      const { caseNum } = c.req.valid("param");

      const data = await db
        .select()
        .from(legalDocument)
        .where(eq(legalDocument.caseNum, caseNum))
        .orderBy(asc(legalDocument.filingDate), desc(legalDocument.trialDate));

      return c.json({ data });
    }
  )
  .post(
    "/get_legal_document_by_case_num",
    zValidator(
      "json",
      z.object({
        query_conds: z.object({
          案号: z.string()
        }),
      })
    ),
    async (c) => {
      const { query_conds } = c.req.valid("json");
      console.log('query_conds', query_conds)
      const data = await db
        .select()
        .from(legalDocument)
        .where(eq(legalDocument.caseNum, query_conds['案号']));

      if (!data[0]) {
        return c.json({ error: "Something went wrong" }, 400);
      }

      return c.json({ data: data[0] });
    }
  )
  .post(
    "/get_legal_document_by_pd",
    zValidator(
      "json",
      z.object({
        query_conds: z.object({
          关联公司: z.string(),
        }),
      })
    ),
    async (c) => {
      const { query_conds } = c.req.valid("json");

      const data = await db
        .select()
        .from(legalDocument)
        .where(
          or(
            eq(legalDocument.plaintiff, query_conds['关联公司']),
            eq(legalDocument.defendant, query_conds['关联公司'])
          )
        );

      return c.json({ data: data });
    }
  );

export default app;
